import { useEffect, useState } from 'react';

import { useParams } from 'react-router-dom';

import { ArrowLeftOutlined } from '@ant-design/icons';

import {
  deviceManagerDetailApi,
  deviceManagerReportApi,
  type DeviceItemDetail,
  type SysUploadDataOldType,
} from '@/api/deviceManagerApi';
import ExpandableDescriptions from '@/components/ExpandableCard/ExpandableDescriptions';
import { ProductNodeType, DeviceListStatus, DeviceCreateTypeList, getEnumItem } from '@/constants';
import { useRouter } from '@/hooks/useRouter';
import { renderValue } from '@/utils/renderUtils';

import EventRecords from './tabs/EventRecords';
import FileRecords from './tabs/FileRecords';
import PropertyRecords from './tabs/PropertyRecords';
import RealTimeMonitoring from './tabs/RealTimeMonitoring';
import ServiceRecords from './tabs/ServiceRecords';

/**
 * 设备详情页
 */
const DeviceDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { back } = useRouter();
  const [loading, setLoading] = useState(true);
  const [deviceDetail, setDeviceDetail] = useState<DeviceItemDetail | null>(null);
  const [reportData, setReportData] = useState<SysUploadDataOldType | null>(null);
  const [reportLoading, setReportLoading] = useState(false);
  const [activeTabKey, setActiveTabKey] = useState('realTimeMonitoring');
  const [selectedAttributeName, setSelectedAttributeName] = useState<string | undefined>();

  // 切换到属性记录页面
  const handleSwitchToPropertyRecords = (attributeName?: string) => {
    setSelectedAttributeName(attributeName);
    setActiveTabKey('propertyRecords');
  };

  // 切换到服务记录页面
  const handleSwitchToServiceRecords = () => {
    setActiveTabKey('serviceRecords');
  };

  // 获取设备详情
  const fetchDeviceDetail = async () => {
    if (!id) return;

    try {
      setLoading(true);
      const res = await deviceManagerDetailApi({ id: Number(id) });
      if (res.success) {
        const deviceData = res.data as DeviceItemDetail;
        deviceData.metaDataJson = JSON.parse(deviceData.metaData || '{}');
        setDeviceDetail(deviceData);
        console.log('deviceData', deviceData);
        // 获取设备详情成功后，获取设备上报数据
        if (deviceData.productCode && deviceData.code) {
          fetchDeviceReportData(deviceData.productCode, deviceData.code);
        }
      }
    } catch (error) {
      console.error('获取设备详情失败:', error);
      window.$message.error('获取设备详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取设备上报数据
  const fetchDeviceReportData = async (productCode: string, deviceCode: string) => {
    try {
      setReportLoading(true);
      const res = await deviceManagerReportApi({ productCode, deviceCode });
      if (res.success) {
        setReportData(res.data);
        console.log('设备上报数据:', res.data);
      }
    } catch (error) {
      console.error('获取设备上报数据失败:', error);
      // 不显示错误消息，因为这不是关键功能
    } finally {
      setReportLoading(false);
    }
  };

  useEffect(() => {
    fetchDeviceDetail();
  }, [id]);

  // 获取节点类型标签
  const getNodeTypeTag = (nodeType: number) => {
    const nodeTypeItem = Object.values(ProductNodeType).find(item => item.value === nodeType);
    return nodeTypeItem ? nodeTypeItem.label : '未知';
  };

  // 获取设备状态标签
  const getStatusTag = (status: number) => {
    const statusItem = getEnumItem(DeviceListStatus, String(status));
    return statusItem ? statusItem.label : '未知';
  };

  // 获取创建方式标签
  const getSourceTag = (source: number) => {
    const sourceItem = getEnumItem(DeviceCreateTypeList, String(source));
    return sourceItem ? sourceItem.label : '未知';
  };

  // 处理缩略图显示（预留功能）
  const _getThumbnailImages = (thumbnail?: string) => {
    if (!thumbnail) return [];
    return thumbnail.split(',').filter(url => url.trim());
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-96">
        <ASpin size="large" />
      </div>
    );
  }

  if (!deviceDetail) {
    return (
      <div className="text-center py-8">
        <p>设备详情不存在</p>
        <AButton onClick={back}>返回设备列表</AButton>
      </div>
    );
  }

  return (
    <div className="page-wrapper">
      <div className="page-title">
        <ArrowLeftOutlined className="mx-4" onClick={back} />
        <div className="page-main-title">设备详情</div>
        <div className="page-sub-title">设备详情页提供设备上报数据的查看和设备信息的编辑功能</div>
      </div>
      <div className="page-content-box">
        <div className="page-content">
          <ExpandableDescriptions
            title="基本信息"
            className="mb-6"
            defaultExpanded={false}
            basicItems={[
              <ADescriptions.Item key="deviceName" label="设备名称">
                {renderValue(deviceDetail.deviceName)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="code" label="设备编码">
                {renderValue(deviceDetail.code)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="keyInfo" label="设备密钥">
                {renderValue(deviceDetail.keyInfo)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="status" label="设备状态">
                <ATag color="blue">{getStatusTag(deviceDetail.status || 0)}</ATag>
              </ADescriptions.Item>,
            ]}
            expandedItems={[
              <ADescriptions.Item key="productName" label="所属产品">
                {renderValue(deviceDetail.productName)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="productCode" label="产品编码">
                {renderValue(deviceDetail.productCode)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="nodeType" label="节点类型">
                <ATag color="green">{getNodeTypeTag(deviceDetail.nodeType || 0)}</ATag>
              </ADescriptions.Item>,
              <ADescriptions.Item key="source" label="创建方式">
                <ATag color="orange">{getSourceTag(deviceDetail.source || 0)}</ATag>
              </ADescriptions.Item>,
              <ADescriptions.Item key="imei" label="IMEI号">
                {renderValue(deviceDetail.imei)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="ipAddress" label="IP地址">
                {renderValue(deviceDetail.ipAddress)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="activationTime" label="激活时间">
                {renderValue(deviceDetail.activationTime)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="latestOnlineTime" label="最近在线时间">
                {renderValue(deviceDetail.latestOnlineTime)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="longitude" label="经度">
                {renderValue(deviceDetail.longitude)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="latitude" label="纬度">
                {renderValue(deviceDetail.latitude)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="address" label="位置信息" span={2}>
                {renderValue(deviceDetail.address)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="dataPushUrl" label="数采推送接口" span={2}>
                {renderValue(deviceDetail.dataPushUrl)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="createTime" label="创建时间">
                {renderValue(deviceDetail.createTime)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="locationId" label="位置ID">
                {renderValue(deviceDetail.locationId)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="remark" label="设备描述" span={2}>
                {renderValue(deviceDetail.remark)}
              </ADescriptions.Item>,
              // <ADescriptions.Item key="thumbnail" label="产品图片" span={2}>
              //   {deviceDetail.thumbnail ? (
              //     <ASpace wrap>
              //       {getThumbnailImages(deviceDetail.thumbnail).map((url, index) => (
              //         <AImage
              //           key={index}
              //           width={120}
              //           height={90}
              //           src={url}
              //           alt={`产品图片 ${index + 1}`}
              //           style={{
              //             objectFit: 'cover',
              //             borderRadius: '6px',
              //             border: '1px solid #f0f0f0',
              //           }}
              //         />
              //       ))}
              //     </ASpace>
              //   ) : (
              //     renderValue(null)
              //   )}
              // </ADescriptions.Item>,
            ]}
          />

          {/* 设备监控数据卡片 */}
          <ACard className="mt-6">
            <ATabs
              activeKey={activeTabKey}
              onChange={setActiveTabKey}
              items={[
                {
                  key: 'realTimeMonitoring',
                  label: '实时监控',
                  children: (
                    <RealTimeMonitoring
                      deviceDetail={deviceDetail}
                      reportData={reportData}
                      reportLoading={reportLoading}
                      onSwitchToPropertyRecords={handleSwitchToPropertyRecords}
                      onSwitchToServiceRecords={handleSwitchToServiceRecords}
                    />
                  ),
                },
                {
                  key: 'propertyRecords',
                  label: '属性记录',
                  children: (
                    <PropertyRecords
                      deviceDetail={deviceDetail}
                      reportData={reportData}
                      reportLoading={reportLoading}
                      selectedAttributeName={selectedAttributeName}
                    />
                  ),
                },
                {
                  key: 'eventRecords',
                  label: '事件记录',
                  children: (
                    <EventRecords
                      deviceDetail={deviceDetail}
                      reportData={reportData}
                      reportLoading={reportLoading}
                    />
                  ),
                },
                {
                  key: 'serviceRecords',
                  label: '服务记录',
                  children: (
                    <ServiceRecords
                      deviceDetail={deviceDetail}
                      reportData={reportData}
                      reportLoading={reportLoading}
                    />
                  ),
                },
                {
                  key: 'fileRecords',
                  label: '文件记录',
                  children: (
                    <FileRecords
                      deviceDetail={deviceDetail}
                      reportData={reportData}
                      reportLoading={reportLoading}
                    />
                  ),
                },
              ]}
            />
          </ACard>
        </div>
      </div>
    </div>
  );
};

export default DeviceDetail;
